﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MillerApp.UserControls;
using System.Threading;
using MillerApp.CommonLib.Utility;
using System.Text.RegularExpressions;
using MillerApp.DataContract.MillerDB;
using MillerApp.DataAccess.MillerDB;
using MillerApp.Stock.Common;
using MillerApp.DataContract.Common;
using MillerApp.Business.Stock;

namespace MillerApp.Stock.Others
{
    public partial class SyncSeccodeInfoForm : SubFormBase
    {
        public SyncSeccodeInfoForm()
        {
            InitializeComponent();
        }

        private void SyncSeccodeInfoForm_Load(object sender, EventArgs e)
        {
            this.lblDate.Text = System.DateTime.Now.ToString("yyyy年MM月dd日");
            this.lblDay.Text = CommonLib.Utility.CommonHelper.GetDayOfWeekChinese(System.DateTime.Now.DayOfWeek);
            this.lblMsg.Text = string.Empty;
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            this.lblMsg.Text = "更新中....";
            Thread oThread = null;
            SecurityService service = new SecurityService();
            ParameterizedThreadStart threadStart = new ParameterizedThreadStart(service.AutoUpdateSecurities);
            oThread = new Thread(threadStart);
            DelegateMessageHanldler method = new DelegateMessageHanldler(HanlderMsgMethod);
            oThread.Start(method);

        }

        private object HanlderMsgMethod(Dictionary<string, object> args)
        {
            try
            {
                //增加这个就不会出现以下的异常了
                if(!this.IsHandleCreated)
                {
                    return null;
                }
                foreach (var item in args)
                {
                    DelegateMessageHanldler method = new DelegateMessageHanldler(HanlderMsgMethod2);
                    //窗口关闭的时候会提示以下异常：
                    //在创建窗口句柄之前，不能在控件上调用 Invoke 或 BeginInvoke
                    lblMsg.Invoke(method, args);
                }
            }
            catch { }
            return null;
        }

        private object HanlderMsgMethod2(Dictionary<string, object> args)
        {
            foreach (var item in args)
            {
                lblMsg.Text = item.Value.ToString();
                if (item.Key.Trim().ToLower() == "FINISHED".ToLower())
                {
                    MessageBox.Show(item.Value.ToString());
                }
            }
            return null;
        }

    }
}
